
import Mock from 'mockjs'
let { newsList } = Mock.mock({
  'newsList|40-100': [
    {
      id: Mock.Random.id(),
      title: '@ctitle()',
      content: '@cparagraph(5,8)',
      img_url: '@image("50*50","#ff83fa","#fcfcfc","png","@ctitle()")',
      created_time: '@date(yyyy-MM-dd hh:mm:ss)'
    }
  ]
})

// 根据url获取query参数
const getQuery = (url, name) => {
  const index = url.indexOf('?')
  if (index !== -1) {
    const queryStringArr = url.substring(index + 1).split("&")
    console.log(queryStringArr)
    for (let el of queryStringArr) {
      const item = el.split("=")
      if (item[0] === name) {
        console.log(item)
        return item[1]
      }
    }
  }
  return null
}

// get新闻列表数据。/api/get/news?pageIndex=1&pageSize=10
Mock.mock(/\/api\/get\/news/, 'get', (config) => {
  const total = newsList.length
  // console.log(config)
  const pageIndex = getQuery(config.url, "pageIndex")
  const pageSize = getQuery(config.url, 'pageSize')
  console.log(pageIndex, pageSize, total)
  const start = (pageIndex - 1) * pageSize
  const end = (pageIndex * pageSize)
  // const list = newsList.filter((item, index) => {
  //   if (index > (pageIndex - 1) * pageSize && index < (pageIndex * pageSize)) {
  //     return item
  //   }
  // }
  // )
  const list = newsList.slice(start, end)
  return {
    code: 200,
    message: 'list success',
    list,
    // list: newsList,
    total: total
  }
})

// 增加新闻  /api/add/news
Mock.mock('/api/add/news', 'post', (config) => {
  let { title, content } = JSON.parse(config.body)
  if (!title || !content) return
  newsList.push(Mock.mock({
    title,
    content,
    id: Mock.Random.id(),
    img_url: '@image("50*50","#ff83fa","#fcfcfc","png","@ctitle()")',
    created_time: '@date(yyyy-MM-dd hh:mm:ss)'
  }))
  return {
    code: 200,
    message: 'add success',
  }
})

// 根据id删除新闻 /api/delete/news
Mock.mock('/api/delete/news', 'post', (config) => {
  const { id } = JSON.parse(config.body);
  if (!id) return
  const index = newsList.findIndex(item => {
    return item.id === id
  })
  newsList.splice(index, 1)
  return {
    code: 200,
    message: 'delete success'
  }
})
